package org.jeecg.modules.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.constant.SymbolConstant;
import org.jeecg.common.constant.enums.RoleIndexConfigEnum;
import org.jeecg.common.desensitization.annotation.SensitiveEncode;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SysUserCacheInfo;
import org.jeecg.common.util.*;
import org.jeecg.config.mybatis.MybatisPlusSaasConfig;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.mapper.*;
import org.jeecg.modules.system.model.SysUserSysDepartModel;
import org.jeecg.modules.system.service.ISysRegService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.vo.SysUserDepVo;
import org.jeecg.modules.system.vo.UserAvatar;
import org.jeecg.modules.system.vo.lowapp.DepartAndUserInfo;
import org.jeecg.modules.system.vo.lowapp.DepartInfo;
import org.jeecg.modules.system.vo.lowapp.UpdateDepartInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @Author: scott
 * @Date: 2018-12-20
 */
@Service
@Slf4j
public class SysRegServiceImpl   implements ISysRegService {
	@Value(value = "${jeecg.domainUrl.Dpuburl}")
	private String Dpuburl;
	@Value(value = "${jeecg.path.thumbnail}")
	private String thumbnail;
	@Value(value = "${jeecg.path.upload}")
	private String uploadpath;
	@Autowired
	private SysRegMapper regMapper;
	public Boolean loginreg (){
		String code = regMapper.getregcode();
		try {
			String contentByAES = ZzSecurityHelper.decryptAES(code);
			String SerialNumber = ZzSecurityHelper.getSerialNumber();
			JSONObject tmpret= JSONObject.parseObject(contentByAES);
			if (SerialNumber.equals(tmpret.get("SerialNumber").toString())){
				String reg = tmpret.get("reg").toString();
				if (reg.equals("1")){
					return true;
				}else{
					long timetamp =  Long.parseLong(tmpret.getString("reg"));;
					SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
					Date date = new Date(timetamp* 1000);
					Date nate = new Date();
					if (nate.compareTo(date) > 0){
						return false;
					}
				}
			}else {
				return false;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	public JSONObject getregwj(){
		JSONObject  tmp2 = new JSONObject();
		try {

			String SerialNumber = ZzSecurityHelper.getSerialNumber();
			String ip = ZzSecurityHelper.getip();
			String hostname = ZzSecurityHelper.gethostname();
			Date date = new Date();
			long timestamp = date.getTime();
			JSONObject tmp = new JSONObject();
			tmp.put("SerialNumber", SerialNumber);
			tmp.put("ip", ip);
			tmp.put("hostname", hostname);
			tmp.put("sqTime", timestamp);
			String redata = "";
			try {
				redata = ZzSecurityHelper.encryptAES(tmp.toJSONString());
			} catch (Exception e) {
				e.printStackTrace();
			}
			String url = Dpuburl;
			String ctxPath = uploadpath;
			String ttxPath = thumbnail;
			String fileName = System.currentTimeMillis() + ".dx";
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
			File f = new File(ctxPath + df.format(new Date()));
			if (!f.exists())
				f.mkdirs();
			File tf = new File(ttxPath + df.format(new Date()));
			if (!tf.exists())
				tf.mkdirs();
			String path = f.getAbsolutePath();
			String destFile = path + "/" + fileName;
			url = url + df.format(new Date()) + "/" + fileName;
			File outputFile = new File(destFile);
			try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
				writer.write(redata);
			} catch (IOException e) {
				e.printStackTrace();
			}
			tmp2.put("code", 0);
			tmp2.put("msg", "上传成功");
			tmp2.put("url",url);
		}catch (Exception e){
			tmp2.put("code", 1);
			tmp2.put("msg", "上传失败");
		}
		return  tmp2;
	}

	public JSONObject upregwj(String file){
		JSONObject tmp = new JSONObject();
		try
		{
			String url = Dpuburl;
			String ctxPath = uploadpath;
			String ttxPath = thumbnail;
			file = file.replace(url,ctxPath);
			BufferedReader reader = null;
			reader = new BufferedReader(new FileReader(file));
			String line;
			String regdata = "";
			// 逐行读取txt文件内容并输出
			while ((line = reader.readLine()) != null) {
				regdata= line;
			}

			reader.close();
			String data = ZzSecurityHelper.decryptAES(regdata);
			JSONObject sj =  JSONObject.parseObject(data);
			String SerialNumber = sj.getString("SerialNumber");
			String ip = sj.getString("ip");
			String SerialNumber_my = ZzSecurityHelper.getSerialNumber();
			if (SerialNumber.equals(SerialNumber_my)){
				long timetamp =  Long.parseLong(sj.getString("reg"));;
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
				Date date = new Date(timetamp*1000);
				Date nate = new Date();
				if (nate.compareTo(date) > 0){
					tmp.put("code", 1);
					tmp.put("msg", "注册有效期异常");
				}else{
					regMapper.updateregcode(regdata);
					tmp.put("code", 0);
					tmp.put("msg", "注册成功");
				}

			}else {
				tmp.put("code", 1);
				tmp.put("msg", "设备信息不匹配");
			}



		}catch (Exception e){
			tmp.put("code", 1);
			tmp.put("msg", "注册失败");


		}
		return   tmp;
	}
}